<?php 
define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
include($phpbb_root_path . 'common.' . $phpEx);

// Start session management
$user->session_begin();
$auth->acl($user->data);
$user->setup('mods/gallery');

// User logged in?
    if(!$user->data['is_registered'])
    {
      // Login box...
      login_box('', $user->lang['LOGIN']);
    }

// Load the appropriate faq file
switch ($mode)
{
	default:
		$l_title = $user->lang['GALLERY'];
		$user->add_lang(array('mods/gallery',));
	break;
}

	$go = isset($_GET['go']) ? $_GET['go'] : '';
	$max_size = 6*1024*1024;
	$dir = 'pictures/';
	$url = 'http://bt.dianet.info/';
	
	$msg = '';
	$links_all = $thumbs_all = array();
	
	// DON'T CHANGE THIS FILE TYPEs
	$allowed_ext = array('jpeg', 'jpg',	'png', 'gif');

function create_thumb ($dir, $name, $att)
{
	$infile = $dir . $name . $att;
	if ($att == ".jpg" || $att == ".jpeg")
		$im = imagecreatefromjpeg($infile);
	elseif ($att == ".png")
		$im = imagecreatefrompng($infile);
	elseif ($att == ".gif")
		$im = imagecreatefromgif($infile);

	$oh = imagesy($im);
	$ow = imagesx($im);
	$r = $oh/$ow;
	$newh = 200;
	$neww = $newh/$r;
	$outfile = $dir ."thumb_". $name . $att;
	$im1 = imagecreatetruecolor($neww,$newh);
	imagecopyresampled($im1, $im, 0, 0, 0, 0, $neww, $newh, imagesx($im), imagesy($im));
	imagejpeg($im1, $outfile, 75);
	imagedestroy($im);
	imagedestroy($im1);
}

function paste_links($links, $thumbs = '')
{
	global $links_all, $thumbs_all;

	if (is_array($links))
	{
		$link = implode(' ', $links);
		$img  = '[img]'. implode('[/img] [img]', $links) .'[/img]';
		
		if ($thumbs)
	{
			$thumb = '';
			for ($i = 0; $i < count($links); $i++)
		{
			$thumb .= '[url='.$links[$i].'][img]'. $thumbs[$i] .'[/img][/url]';
		}
	}
	}
	else
	{
		$link = trim($links);
		$img  = '[img]'. $links .'[/img]';

		$thumb = '[url='.$link.'][img]'. $thumbs .'[/img][/url]';
	}
	$spoiler = '[spoiler=Скриншоты]' . $img . '[/spoiler]';
	
	$text  = (!is_array($links)) ? '<br /><a href='. $link .' target=_blank>'. $link .'</a><br>' : '';
	$text .= (!is_array($links)) ? '<br /><img src='. $link .' onload="imgFit(this, screen.width-1200);" onload="imgFit(this, 580);" onclick="imgFit(this, 580);" alt="Ваше изображение">' : '';
	$text .= '<br /><br /><h5 align="left"><b>Ссылка на изображение</b><br /><input type="text" readonly="" value="'. $link .'" size="140" onclick="f2(this);"></h5>';
	$text .= '<br /><h5 align="left"><b>Тэг вставки cкриншота:</b><br /><input type="text" readonly="" value="'.$img.'" size="140" onclick="f2(this);"></h5>';
	if ($thumbs)
	{
		$text .='<br /><h5 align="left"><b>Тэг вставки cкриншота с превью:</b><br /><input type="text" readonly="" value="'. $thumb .'" size="140" onclick="f2(this);"></h5>';
	}
	$text .= (!is_array($links)) ? '<br /><h5 align="left"><b>Тэг вставки постера справа:</b><br /><input type="text" readonly="" value="[cover]'. $link .'[/cover]" size="140" onclick="f2(this);"></h5>' : '';
	$text .= '<br /><h5 align="left"><b>Тэг cпойлера:</b><br /><input type="text" readonly="" value=\''. $spoiler .'\' size="140" onclick="f2(this);"></h5>';

	$links_all[] = $links;
	$thumbs ? ($thumbs_all[] = $thumbs) : null;
	
	return $text;
}

function upload_file ($files_ary, $idx)
{
	global $max_size, $allowed_ext, $create_thumb, $dir, $url;

	if (empty($files_ary))
		trigger_error('GALLERY_FILE_BIG');
	if ($files_ary['size'][$idx] > $max_size)
		trigger_error('GALLERY_FILE_BIG_MSG');

	$name = strtolower($files_ary['name'][$idx]);
	$ext  = substr(strrchr($name, '.'), 1);

	$allow = in_array($ext, $allowed_ext);
	$att   = '.'. $ext;

	$thumb = false;

	if ($allow)
	{
		$name = md5_file($files_ary['tmp_name'][$idx]);

		if (file_exists($dir . $name . $att))
		{
			if ($create_thumb && !file_exists($dir .'thumb_'. $name . $att))
			{
				create_thumb($dir, $name, $att);
				$thumb = $url . $dir ."thumb_". $name . $att;
			}
			$msg = '<hr>Такое изображение уже существует. '. paste_links($url . $dir . $name . $att, $thumb) .'</a>';
		}
		else
		{
			if (copy($files_ary['tmp_name'][$idx], $dir.$name.$att))
			{
				if ($create_thumb)
				{
					create_thumb($dir, $name, $att);
					$thumb = $url . $dir ."thumb_". $name . $att;
				}
				$msg = '<hr>Загрузка прошла успешно. '. paste_links($url . $dir . $name . $att, $thumb) .'</a>';
			}
			else $msg = "<hr><span style='color:red'>Загрузка потерпела неудачу. Повторите.</span>";
		}
	}
	else $msg = "<hr><span style='color:red'>Недопустимый тип файла.</span>";

	return $msg;
}

if ($go == 'upload')
	{
	@ini_set("memory_limit", "512M");
	$create_thumb = (isset($_POST['create_thumb'])) ? true : false;

	for ($i = 0; $i < count(@$_FILES['imgfile']['name']); $i++)
	{
	$msg .= upload_file ($_FILES['imgfile'], $i);
	}
	if (count(@$_FILES['imgfile']['name']) > 1)
	{
	$msg .= '<hr />'. paste_links ($links_all, $thumbs_all);
	}
}

if ($go == 'delete' && IS_ADMIN && !empty($_GET['fn']))
{
	$fn = clean_filename($_GET['fn']);

	$pic  = $dir . $fn;
	$prev = $dir ."thumb_". $fn;
	if (!is_file($pic)) trigger_error('GALLERY_FILE_NOT_EXIST');

	if (unlink($pic))
	{
		@unlink($prev);
		trigger_error("<center><span style='color:red'><h2>". $user->lang['GALLERY_FILE_DELETE'] ."</h2></span><br><a href='gallery.php'>". $user->lang['GALLERY_BACK'] ."</a></center>");
	}
	else
		
		trigger_error("<center><span style='color:red'><h2>". $user->lang['GALLERY_FAILURE'] ."</h2></span><br><a href='gallery.php'>". $user->lang['GALLERY_BACK'] ."</a></center>");
		
}

$template->assign_vars(array(
	'MSG'            =>  $msg,
	'MAX_SIZE'       =>  get_formatted_filesize($max_size),
	'MAX_SIZE_HINT'  =>  $user->lang['GALLERY_MAX_FILE_SIZE'],
	'CREATE_THUMB'   =>  $user->lang['GALLERY_CREATE_THUMB'],
	'UPLOAD'         =>  $user->lang['GALLERY_UPLOAD_IMAGE'],
	'MORE'           =>  $user->lang['GALLERY_MORE_LINK'],
));

page_header($l_title);

$template->set_filenames(array(
	'body' => 'gallery_body.html')
);
make_jumpbox(append_sid("{$phpbb_root_path}viewforum.$phpEx"));
page_footer();

?> 